<?php  if ( ! defined('DIR_ROOT')) exit(NO_SCRIPT_ALLOW_NOTICE);
/**
 * 钩子类相关文件，可以通过config/hooks.php 的数组配置来定义钩子运行的函数、时间、参数等
 * 
 * @author	terryhuang
 * @name 	CK_HOOKS.php
 * @cTime	2010-12-31
 * @modify	2011-1-5	terryhuang	添加注释
 * 
 */

/**
 * 钩子类
 * 
 * @author  terryhuang
 * @name 	CK_HOOKS
 * 
 */
class CK_Hooks {

	var $enabled 		= FALSE;
	var $hooks   		= array();
	var $in_progress	= FALSE;

	/**
	 * 构造函数
	 */
	function CK_Hooks()
	{
		$this->_initialize();
		logger('debug', "Hooks Class Initialized");
	}
  
	/**
	 * 初始化，判断全局配置是否允许钩子，并加载config/hooks.php文件
	 * @access	private
	 * @return	none
	 */
  	function _initialize()
  	{
  	    global $ck_config;
		if ($ck_config['enable_hooks'] === FALSE)
		{
			return;
		}
		@include(DIR_CONFIG.'/hooks'.EXT);
		if ( !isset($hook) || ! is_array($hook))
		{
			return;
		}
		$this->hooks =& $hook;
		$this->enabled = TRUE;
  	}
  
	/**
	 * 运行特定钩子
	 * 
	 * @access	private
	 * @param	string	钩子名称
	 * @return	mixed
	 */
	function _call_hook($which = '')
	{
		if (!( $this->enabled && isset($this->hooks[$which])))
		{
			return FALSE;
		}
		if (isset($this->hooks[$which][0]) && is_array($this->hooks[$which][0]))
		{
			foreach ($this->hooks[$which] as $val)
			{
				$this->_run_hook($val);
			}
		}
		else
		{
			$this->_run_hook($this->hooks[$which]);
		}
		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * 
	 *
	 * @access	private
	 * @param	array	the hook details
	 * @return	bool
	 */
	function _run_hook($data)
	{
		if ( ! is_array($data))
		{
			return FALSE;
		}
		if ($this->in_progress === TRUE)
		{
			return;
		}

		if ( ! isset($data['filepath']) OR ! isset($data['filename']))
		{
			return FALSE;
		}
		if ( $data['filepath'] == "")
		{
		    $filepath = DIR_HOOK.'/'.$data['filename'];
		}
		else
		{
		    $filepath = DIR_HOOK.'/'.$data['filepath'].'/'.$data['filename'];
		}
		if ( ! file_exists($filepath))
		{
			return FALSE;
		}

		$class		= FALSE;
		$function	= FALSE;
		$params		= '';

		if (isset($data['class']) && $data['class'] != '')
		{
			$class = $data['class'];
		}

		if (isset($data['function']))
		{
			$function = $data['function'];
		}

		if (isset($data['params']))
		{
			$params = $data['params'];
		}

		if ($class === FALSE && $function === FALSE)
		{
			return FALSE;
		}
		$this->in_progress = TRUE;
		
		if ($class !== FALSE)
		{
			if ( !class_exists($class))
			{
				require($filepath);
			}

			$HOOK = new $class;
			$HOOK->$function($params);
		}
		else
		{
			if ( ! function_exists($function))
			{
				require($filepath);
			}
			$function($params);
		}

		$this->in_progress = FALSE;
		return TRUE;
	}
}
